let utils = {
  template: {
    induction: 1,
  },

  /**
   * 时间戳转换，当天返回 hh:mm，一天以前返回 n天前
   * @param timestamp
   * @returns {string}
   */
  toChatFormatTimeDiff: function (timestamp) {
    // 获取时间戳对应的日期时间，格式 yyyy-MM-dd hh:mm:ss
    var lasttime = this.timestampToFormatDatetime(timestamp);
    // 获取当前系统日期时间，格式 yyyy-MM-dd hh:mm:ss
    var curtime = this.getCurDatetime();

    var lastDate = new Date(lasttime.substr(0, 4), lasttime.substr(5, 2) - 1,
      lasttime.substr(8, 2), lasttime.substr(11, 2), lasttime.substr(14, 2),
      lasttime.substr(17, 2));
    var curDate = new Date(curtime.substr(0, 4), curtime.substr(5, 2) - 1,
      curtime.substr(8, 2), curtime.substr(11, 2), curtime.substr(14, 2),
      curtime.substr(17, 2));

    var dateDifference = curDate.getTime() - lastDate.getTime();//时间差的毫秒数
    var days = Math.floor(dateDifference / (24 * 3600 * 1000))//计算出相差天数
    //计算出小时数
    var leave1 = dateDifference % (24 * 3600 * 1000);    //计算天数后剩余的毫秒数
    var hours = Math.floor(leave1 / (3600 * 1000));
    //计算相差分钟数
    var leave2 = leave1 % (3600 * 1000);        //计算小时数后剩余的毫秒数
    var minutes = Math.floor(leave2 / (60 * 1000));
    //计算相差秒数
    var leave3 = leave2 % (60 * 1000);      //计算分钟数后剩余的毫秒数
    var seconds = Math.round(leave3 / 1000);
    var retDate = days + "天 " + hours + "小时 " + minutes + "分钟 " + seconds + "秒";

    if (days > 0) {
      retDate = days + '天前'
    } else {
      retDate = lasttime.substr(11, 5);
    }
    // console.log("result date : " + retDate);
    return retDate;
  },
  /**
   * 时间戳转换为 yyyy-MM-dd hh:mm:ss
   * @param timestamp
   * @returns {string}
   */
  timestampToFormatDatetime: function (timestamp) {
    var end = new Date(timestamp);
    var endyear = this.fix(end.getFullYear(), 4);
    var endmonth = this.fix(parseInt(end.getMonth() + 1), 2);
    var endday = this.fix(end.getDate(), 2);
    var endhours = this.fix(end.getHours(), 2);
    var endminutes = this.fix(end.getMinutes(), 2);
    var endseconds = this.fix(end.getSeconds(), 2);
    var curtime = endyear + '-' + endmonth + '-' + endday + ' ' + endhours + ':'
      + endminutes + ':' + endseconds;
    return curtime;
  },
  /**
   * 时间转换为 yyyy-MM-dd
   * @param date
   * @returns {string}
   */
  dateToDate: function (date) {
    var end = new Date(date);
    var endyear = this.fix(end.getFullYear(), 4);
    var endmonth = this.fix(parseInt(end.getMonth() + 1), 2);
    var endday = this.fix(end.getDate(), 2);
    var curtime = endyear + '-' + endmonth + '-' + endday;
    return curtime;
  },
  /**
   * 时间转换为 yyyy/MM/dd
   * @param date
   * @returns {string}
   */
  dateToDate2: function (date) {
    var end = new Date(date);
    var endyear = this.fix(end.getFullYear(), 4);
    var endmonth = this.fix(parseInt(end.getMonth() + 1), 2);
    var endday = this.fix(end.getDate(), 2);
    var curtime = endyear + '/' + endmonth + '/' + endday;
    return curtime;
  },
  /**
   * 时间转换为 yyyy-MM
   * @param date
   * @returns {string}
   */
  dateToMonth: function (date) {
    var end = new Date(date);
    var endyear = this.fix(end.getFullYear(), 4);
    var endmonth = this.fix(parseInt(end.getMonth() + 1), 2);
    var curtime = endyear + '-' + endmonth;
    return curtime;
  },
  /**
   * 时间转换为 yyyy年MM月dd日
   * @param date
   * @returns {string}
   */
  dateToDateString: function (date) {
    var end = new Date(date);
    var endyear = this.fix(end.getFullYear(), 4);
    var endmonth = this.fix(parseInt(end.getMonth() + 1), 2);
    var endday = this.fix(end.getDate(), 2);
    var curtime = endyear + '年' + endmonth + '月' + endday + '日';
    return curtime;
  },
  /**
   * 时间转换为 HH:mm
   * @param date
   * @returns {string}
   */
  dateToTime: function (date) {
    var end = new Date(date);
    var endhours = this.fix(end.getHours(), 2);
    var endminutes = this.fix(end.getMinutes(), 2);
    var curtime = endhours + ':' + endminutes;
    return curtime;
  },
  /**
   * 秒转换为时间
   * @param times
   * @returns {string}
   */
  timesToTime: function (times) {
    var curtime = '';
    if (times >= 0 && times < 60) {
      curtime = times + '秒';
    } else if (times >= 60 && times < (60 * 60)) {
      var mm = parseInt(times / 60);
      var ss = times % 60;
      curtime = mm + '分' + ss + '秒';
    } else if (times >= (60 * 60) && times < (60 * 60 * 24)) {
      var hh = parseInt(times / (60 * 60));
      var mm = parseInt(times % (60 * 60) / 60);
      var ss = times % (60 * 60) % 60;
      curtime = hh + '小时' + mm + '分' + ss + '秒';
    } else if (times >= (60 * 60 * 24)) {
      var dd = parseInt(times / (60 * 60 * 24));
      var hh = parseInt((times % (60 * 60 * 24)) / (60 * 60));
      var mm = parseInt((times % (60 * 60 * 24)) % (60 * 60) / 60);
      var ss = ((times % (60 * 60 * 24)) % (60 * 60)) % 60;
      curtime = dd + '天' + hh + '小时' + mm + '分' + ss + '秒';
    }
    return curtime;
  },
  /**
   * 设置数字几位数显示；例console.log(fix(5, 2));输出结果为05
   * @param num
   * @param length
   * @returns {string}
   */
  fix: function (num, length) {
    return ('' + num).length < length ? ((new Array(length + 1)).join('0')
    + num).slice(-length) : '' + num;
  },
  /**
   * 获取当前系统时间并按照一定格式返回
   * @returns {string} format{yyyy-MM-dd HH:mm:ss}
   */
  getCurDatetime: function () {
    var end = new Date();
    var endyear = this.fix(end.getFullYear(), 4);
    var endmonth = this.fix(parseInt(end.getMonth() + 1), 2);
    var endday = this.fix(end.getDate(), 2);
    var endhours = this.fix(end.getHours(), 2);
    var endminutes = this.fix(end.getMinutes(), 2);
    var endseconds = this.fix(end.getSeconds(), 2);
    var curtime = endyear + '-' + endmonth + '-' + endday + ' ' + endhours + ':'
      + endminutes + ':' + endseconds;
    return curtime;
  },
  computeFileSize: function (size) {
    size = (size / 1024).toFixed(2);//K
    if (size > 1024) {
      size = (size / 1024).toFixed(2);//M
      size = size + 'M';
    } else {
      size = size + 'K';
    }
    return size;
  },
  convertImgToDataURLviaCanvas: function (url, callback, outputFormat) {
    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function () {
      var canvas = document.createElement('CANVAS');
      var ctx = canvas.getContext('2d');
      var dataURL;
      canvas.height = this.height;
      canvas.width = this.width;
      ctx.drawImage(this, 0, 0);
      dataURL = canvas.toDataURL(outputFormat);
      //dataURL = canvas.toDataURL('image/jpeg'); //转换图片为dataURL
      callback(dataURL);
      canvas = null;
    };
    img.src = url;
  },
  checkNumber: function (number) {
    //正则：验证数字 大于0
    var reg = /^\+?[1-9][0-9]*$/;
    if (!reg.test(number)) {
      return false;
    }
    else {
      return true;
    }
  },
  checkMobile: function (phone) {
    //正则：验证电话号码手机号码，包含至今所有号段
    var reg = /^(1[3|4|5|7|8])[\d]{9}$/;
    if (!reg.test(phone)) {//alert("电话号码格式错误!");obj.value="";obj.focus();
      return false
    }
    else {//alert("您的电话号码:"+phone);
      return true
    }
  },
  UrlEncode: function (str) {
    function str2asc(strstr) {
      return ("0" + strstr.charCodeAt(0).toString(16)).slice(-2)
    }

    function asc2str(ascasc) {
      return String.fromCharCode(ascasc)
    }

    var ret = "";
    var strSpecial = "!\"#$%&'()*+,/:;<=>?[]^`{|}~%";
    var tt = "";

    for (var i = 0; i < str.length; i++) {
      var chr = str.charAt(i);
      var c = str2asc(chr);
      tt += chr + ":" + c + "n"
      if (parseInt("0x" + c) > 0x7f) {
        ret += "%" + c.slice(0, 2) + "%" + c.slice(-2)
      } else {
        if (chr == " ")
          ret += "+"
        else if (strSpecial.indexOf(chr) != -1)
          ret += "%" + c.toString(16)
        else
          ret += chr
      }
    }
    return ret
  },
  toStr: function (obj) {
    var res = '';
    if (typeof obj == 'string') {
      res = obj
    } else if (typeof obj == 'object') {
      res = JSON.stringify(obj)
    }
    return res
  },
  toJson: function (str) {
    var res = ''
    if (str != '' && str != undefined && str != null) {
      if (typeof str == 'string') {
        str = str.trim()
        res = JSON.parse(str) ? JSON.parse(str) : eval('(' + str + ')')
      } else if (typeof str == 'object') {
        res = str
      }
    }
    return res
  },
  /**
   * 设置固定过期时间的cookies
   */
  setCookie: function (name, value, Days) {
    var Days = Days ? Days : 30
    var exp = new Date()
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000)
    document.cookie = name + "=" + escape(value) + ";expires="
      + exp.toGMTString()
  },
  /**
   * 读取cookies
   */
  getCookie: function (name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); //正则匹配
    if (arr = document.cookie.match(reg)) {
      return unescape(arr[2])
    }
    else {
      return null
    }
  },
  /**
   * 删除cookies
   */
  delCookie: function (name) {
    var exp = new Date()
    exp.setTime(exp.getTime() - 1)
    var cval = getCookie(name)
    if (cval != null) {
      document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString()
    }
  },
  /**
   * 加密
   */
  compile: function (code) {
    var c = String.fromCharCode(code.charCodeAt(0) + code.length)
    for (var i = 1; i < code.length; i++) {
      c += String.fromCharCode(code.charCodeAt(i) + code.charCodeAt(i - 1))
    }
    return escape(c)
  },
  /**
   * 解密
   */
  uncompile: function (code) {
    code = unescape(code)
    var c = String.fromCharCode(code.charCodeAt(0) - code.length)
    for (var i = 1; i < code.length; i++) {
      c += String.fromCharCode(code.charCodeAt(i) - c.charCodeAt(i - 1))
    }
    return c
  },
  /**
   * 判断元素id是否存在于arr数组中，存在返回true，不存在返回false
   * @param arr
   * @param id
   * @returns {boolean}
   */
  idInArray: function (id, arr) {
    var _this = this
    var len = arr.length
    var total = 0
    for (var i = 0; i < len; i++) {
      if (arr[i].id == id) {
        total = parseInt(total) + 1
        break
      }
    }
    return (parseInt(total) > 0) ? true : false
  },
  inArray: function (val, arr) {
    var _this = this
    var len = arr.length
    var total = 0
    for (var i = 0; i < len; i++) {
      if (arr[i] == val) {
        total = parseInt(total) + 1
        break
      }
    }
    return (parseInt(total) > 0) ? true : false
  },
  // 下载文件
  FileDownloader: function (url, name) {
    new FileDownloader({
      url: encodeURI(url),
      filename: name
    })
  },
  // 下载文件
  DownloadFile: function (url, name) {
    try {
      var DownloadFile_a_id = document.getElementById('DownloadFile_a_id')
      DownloadFile_a_id.href = url
      DownloadFile_a_id.download = name
      DownloadFile_a_id.click()
    } catch (e) {

    }
  },
  // 深复制对象方法
  cloneObj: function (obj) {
    var newObj = {}
    if (obj instanceof Array) {
      newObj = []
    }
    for (var key in obj) {
      var val = obj[key]
      newObj[key] = typeof val === 'object' ? this.cloneObj(val) : val
    }
    return newObj
  },
  // 深复制数组方法
  copyArr: function (arr) {
    let res = []
    for (let i = 0; i < arr.length; i++) {
      res.push(arr[i])
    }
    return res
  },
  // 合并数组并去重
  mergeArray: function (arr2, arr1) {
    for (var i = 0; i < arr1.length; i++) {
      for (var j = 0; j < arr2.length; j++) {
        if (arr1[i] === arr2[j]) {
          arr1.splice(i, 1)
        }
      }
    }
    for (var ii = 0; ii < arr1.length; ii++) {
      arr2.push(arr1[ii])
    }
    return arr2
  },
  // 数组去重
  onlyArray: function (array) {
    var temp = []
    for (var i = 0; i < array.length; i++) {
      if (temp.indexOf(array[i]) <= -1) {
        temp.push(array[i])
      }
    }
    return temp
  },
  // 生成随机数
  generateRandom: function (arr) {
    var temp = []
    var count = arr.length
    for (var i = 0; i < count; i++) {
      var num = Math.floor(Math.random() * arr.length)
      temp.push(arr[num])
      arr.splice(num, 1)
    }
    return temp
  },
  // 获取随机数
  getRandom: function () {
    var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e']
    var numArr = this.generateRandom(arr)
    var str = ''
    for (var k in numArr) {
      if (!numArr[k]) {
        continue
      }
      var val = numArr[k].toString()
      str += val
    }
    return str
  },
  // 判断是不是数组
  isArrayFn: function (arr) {
    if (typeof Array.isArray === 'function') {
      return Array.isArray(arr)
    } else {
      return Object.prototype.toString.call(arr) === '[object Array]'
    }
  },
  // 判断当前用户是：管理员、正领导、副领导
  is_leadership: function () {
    var leadership = false
    var departments = this.toJson(localStorage.getItem('userInfo')).departments || []
    for (var k in departments) {
      if (!departments[k]) {
        continue
      }
      var position = departments[k].position || []
      for (var p in position) {
        if (!position[p]) {
          continue
        }
        var pos = [1, 2, 3]
        var id = position[p].id
        if (pos.indexOf(id) > -1) {
          leadership = true
          break
        }
      }
    }
    return leadership
  }
}
export default utils
